package cn.mong.util.modelexcel;

import java.awt.Point;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import lombok.extern.slf4j.Slf4j;

/**
 * 注解驱动的数据模型excel写入器
 * 
 * @author mengxianming@2021-9-15 9:48:12
 *
 * @param <D>
 */
@Slf4j
public class DynaHeaderAnnotationModelWriter<D> extends HeaderAnnotationModelWriter<D>{
	
    public DynaHeaderAnnotationModelWriter(Class<D> modelClazz,  CellWriter cellWriter) {
        super(modelClazz, cellWriter, null);
    }

    public DynaHeaderAnnotationModelWriter(Class<D> modelClazz,  CellWriter cellWriter, HeaderCustomizer headerCustomizer) {
        super(modelClazz, cellWriter, headerCustomizer);

    }


    @Override
    public Point writeModels(Iterable<D> models, boolean writeHeader) {
        // 获取所有模型的值单元格
        List<ValCell> valCells = new ArrayList<>();
        for(D model : models) {
            valCells.addAll(this.modelToValCells(model));
        }
        
        // 按照列头id分组。key为列头id，value为该列头的最大合并列数。
        Map<Integer, Integer> headerIdToMaxXSpan = new HashMap<>();
        valCells.forEach(vc -> {
            headerIdToMaxXSpan.compute(vc.getHeader().getId(),
                    (k, v) -> v == null ? vc.getCol() + vc.getXspan() : Math.max(v, vc.getCol() + vc.getXspan()));
        });
        
        // 重新计算列头的合并列数
        headerResolver.getFlatHeaders().forEach(fh -> {
            if(headerIdToMaxXSpan.containsKey(fh.getId())) {
                fh.setXspan(headerIdToMaxXSpan.get(fh.getId()));
            }
        });
        
        // 重新计算列头的列号
        headerResolver.calculateHeaderCol();
        
        return super.writeModels(models, writeHeader);
    }


    @Override
    public boolean supportWriteHorizontal() {
    	return true;
    }
    
}